<?php /* УТФ-8:fix */

class SPIcontroller__filters__manage extends SPIcontroller__filters
{
    private $CONTENT_MODES = array(); 

    public function __construct()
    {
        parent::__construct();

        $this->CONTENT_MODES = array(
            'product' => SPI::I('lang')->filters->typename['product'],
        );

        return;
    }

    public function gen_menu()
    {
        $menuitems = array();

        $in_topic = SPI::I('var')->get('topic');
        $in_tmode = SPI::I('var')->get('tmode');

        $toolbar_attrs = array(
            'product'     => array( 'toolbar'=>'MAIN',  'align_prior'=>1 ),
        );

        foreach( array_keys( $this->CONTENT_MODES ) as $one_tmode )
        {
            $menuitems[ $toolbar_attrs[$one_tmode]['toolbar'] ][] = array(
                'access'        => array( SPI_IAM_PERM_ADMIN ),
                'link'          => $this->pack_link( $one_tmode, array( 'cat' => false ) ),
                'icon'          => "params__manage_{$one_tmode}.gif",
                'name'          => SPI::I('lang')->filters->{"menu_{$one_tmode}"},
                'is_active'     => $in_topic == $this->CONTROLLER_ID && $in_tmode == $one_tmode,
                'align_prior'   => $toolbar_attrs[$one_tmode]['align_prior'],
            );
        }

        return $menuitems;
    }

    public function pack_link( $mode = null, $vars = null, $isToCatalogs = false )
    {
		if( isset( $vars['cat'] ) === false )
		{
			$cat = SPI::I('var')->get('cat');
			if( !empty( $cat ) )
				$vars['cat'] = (int) $cat;
		}
		elseif( empty( $vars['cat'] ) )
		{
			unset($vars['cat']);
		}
		
		if( isset( $vars['pid'] ) === false )
		{
			$pid = SPI::I('var')->get('pid');
			if( !empty( $pid ) )
				$vars['pid'] = (int) $pid;
		}
		elseif( empty( $vars['pid'] ) )
		{
			unset($vars['pid']);
		}
		
		if( $isToCatalogs )
			return SPIc::I('manage')->link->pack( 'catalogs__manage', $mode, $vars );
		
		return SPIc::I('manage')->link->pack( $this->CONTROLLER_ID, $mode, $vars );
    }

    public function exec( & $content )
    {
        $data = array();

        $data['topic']  = SPI::I('var')->get('topic');
        $data['tmode']  = SPI::I('var')->get('tmode');
        $data['action'] = SPI::I('var')->get('action');
        $data['pid']    = SPI::I('var')->get('pid') ? SPI::I('var')->get('pid') : null;

        if( SPI::I('Iam')->is_permit( SPI_IAM_PERM_ADMIN ) !== true )
        {
            return false;
        }

        if( in_array( $data['tmode'], array_keys( $this->CONTENT_MODES ) ) === false )
        {
            return false;
        }

        switch( $data['action'] )
        {
            default:
            {
                $data['action'] = 'view';
            }
            case 'view':
            {
                if( $this->exec_view( $content, $data ) === false )
                {
                    return false;
                }
                break;
            }

            case 'sort':
            {
                $this->exec_sortdata( $content, $data );
                break;
            }

            case 'insert':
            case 'modify':
            {
                $this->exec_savedata( $content, $data ); # => die by json-data response
            }

            case 'form':
            {
                if( $this->exec_form( $content, $data ) === false )
                {
                    return false;
                }
                break;
            }
        }

        $content['data'] = $data;

        return true;
    }

    private function exec_view( & $content, & $data, $is_recursive_exec = false )
    {
        if( false === ( $mFilters = SPIm::I('filters') ) )
        {
            return false;
        }

        $data['title']    = SPI::I('lang')->content->{"title_{$data['tmode']}"};
        $data['subtitle'] = SPI::I('lang')->manage->viewmode_list;
        $data['template'] = 'filters/view.tpl';

        $action_do = SPI::I('var')->get('action_do');
		$cat       = SPI::I('var')->get('cat');
		
        $data['CONTENT_MODES'] = $this->CONTENT_MODES;

        $data['link_newitem'] = $this->pack_link( $data['tmode'], array( 'action'=>'form' ) );
        $data['link_sort'] = $this->pack_link( $data['tmode'], array( 'action'=>'sort' ) );
		if( $data['pid'] )
		{
			$data['link_back'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'pid' => false ) );
		}
		else
		{
			$cat_item = SPIm::I('catalogs')->manage->get_by_id($cat);
			$data['link_back'] = $this->pack_link( 'catalog', array( 'action'=>'view', 'pid' => $cat_item['pid'], 'cat' => false ), true );
        }
		
		// --------------------------------------------------------------------
		
        if( $is_recursive_exec === false) // if $is_recursive_exec == true --> don't need to ReExecute action
        if( in_array( $action_do, array( 'activity_on', 'activity_off', 'delete' ) ) === true )
        {
            $id_list = SPI::I('var')->get( 'multiselect' );
            
            if( is_array( $id_list ) === false )
            {
                $id_list[] = SPI::I('var')->get( 'iid' );
            }

            foreach( $id_list as $item_id )
            {
                $item_id = (int) $item_id;

                if( $item_id == 0 )
                {
                    continue;
                }

                switch( $action_do )
                {
                    case 'activity_on':  $mFilters->manage->set_activity( 'on', $item_id ); break;
                    case 'activity_off': $mFilters->manage->set_activity( 'off', $item_id ); break;
                    case 'delete':
                    {
                        $mFilters->manage->delete( $item_id );
                        break;
                    }
                }
            }
            unset( $id_list, $item_id );

            SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_operation_complite );
        }

        if( $action_do == 'set_sort_order' )
        {
            $new_sort_order = trim( SPI::I('var')->get('new_sort_order'), ',' );
            $new_sort_order = explode( ',', $new_sort_order );

            SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_modify_complite );

            if( count( $new_sort_order ) > 0 )
            {
                SPIm::I('filters')->manage->reset_order_indexes( $data['tmode'], $cat, $data['pid'] );

                $index = 1;
                foreach( $new_sort_order as $sort_item_id )
                {
					SPIm::I('filters')->manage->modify( $sort_item_id, array( 'order_index'=>$index++ ) );
                }
            }
        }

        // --------------------------------------------------------------------
        // Make notifications by 'action_complite' value

        switch( SPI::I('var')->get('action_complite') )
        {
            case 'insert': SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_insert_complite ); break;
            case 'modify': SPIc::I('manage')->notifier->set_message( $content, true, SPI::I('lang')->notifier->msg_modify_complite ); break;
        }

        // --------------------------------------------------------------------
        // Filter objects [stdobj]

        $stdobj_baseurl = $this->pack_link( $data['tmode'], array( 'action'=>'view' ) );

        $content['stdobj']['f_search'] = SPIc::I('manage')->stdobj->filter(
            "{$data['topic']}:{$data['tmode']}",
            "search",
            $stdobj_baseurl
        );

        // --------------------------------------------------------------------
        // Order fields [stdobj]

        $orderfields_array = array( 'order_index+', 'name+', 'method_equal+', 'value+', 'description+', 'id+' );

        $content['stdobj']['order'] = SPIc::I('manage')->stdobj->order(
            "{$data['topic']}:{$data['tmode']}",
            $stdobj_baseurl,
            $orderfields_array
        );

        // --------------------------------------------------------------------

        $qresult = $mFilters->manage->select(
            $data['tmode'],
			$cat,
			$data['pid'],
            $content['stdobj']['f_search']['value'],
            $content['stdobj']['order']['current']
        );

        if( $qresult === false )
        {
            return false;
        }
        
        $data['items_count'] = $qresult->num_rows();

        // --------------------------------------------------------------------
        // Pager [stdobj]

        $content['stdobj']['pager'] = SPIc::I('manage')->stdobj->pager(
            "{$data['topic']}:{$data['tmode']}",
            $stdobj_baseurl,
            $data['items_count']
        );

        // --------------------------------------------------------------------
        // Generate List

        $qresult->seek( $content['stdobj']['pager']['firstitem_index'] );
        $qresult->set_manual_limit( $content['stdobj']['pager']['items_per_page'] );

        $data['items'] = array();

        while( $item = $qresult->fetch() )
        {
            $item['method_equal'] = $this->availMethods[$item['method_equal']];
			
			if( $data['pid'] )
			{
				$paramItem = SPIm::I('params')->manage->get_by_id($item['pid_params']);
				$item['param'] = $paramItem['name'];
			}
			else
			{
				$item['link_subitems'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'pid'=>$item['id'] ) );
			}
			
			$item['link_modify'] = $this->pack_link( $data['tmode'], array( 'action'=>'form', 'iid'=>$item['id'] ) );
            $item['link_delete'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_do'=>'delete', 'iid'=>$item['id'] ) );

            if( $item['workstatus'] == '0' )
            {
                $item['link_activity_on'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_do'=>'activity_on', 'iid'=>$item['id'] ) );
            }
            elseif( $item['workstatus'] == '1' ) 
            {
                $item['link_activity_off'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_do'=>'activity_off', 'iid'=>$item['id'] ) );
            }

            $data['items'][ $item['id'] ] = $item;
        }
        $qresult->close();

        if( count( $data['items'] ) == 0 && $data['items_count'] != 0 && $is_recursive_exec === false )
        {
            // Reset page index to number '1'
            SPIc::I('manage')->stdobj->pager_reset( "{$data['topic']}:{$data['tmode']}" );

            // Recursive run
            return $this->exec_view( $content, $data, true );
        }

        // --------------------------------------------------------------------

        $data['formvars'] = array();
        $data['formvars']['tmode']  = $data['tmode'];
        $data['formvars']['action'] = $data['action'];
        $data['formvars']['cat']    = $cat;
        $data['formvars']['pid']    = $data['pid'];

        $data['link_form_submit'] = $this->pack_link( $data['tmode'], array( 'cat'=>$cat ) );

        // --------------------------------------------------------------------

        return true;
    }

    private function exec_form( & $content, & $data )
    {
        if( false === ( $mFilters = SPIm::I('filters') ) )
        {
            return false;
        }

        $data['title']    = SPI::I('lang')->filters->{"title_{$data['tmode']}"};
        $data['subtitle'] = '';
        $data['template'] = 'filters/form.tpl';

        $data['link_back'] = $this->pack_link( $data['tmode'] );

        $item_id = (int) SPI::I('var')->get( 'iid' );
        $cat = (int) SPI::I('var')->get( 'cat' );

        if( $item_id )
        {
            $data['formmode'] = 'modify';
            $data['subtitle'] = SPI::I('lang')->manage->viewmode_form_update;

            $item_fields = SPIm::I('filters')->manage->get_by_id( $item_id );
        }
        else
        {
            $data['formmode'] = 'insert';
            $data['subtitle'] = SPI::I('lang')->manage->viewmode_form_newitem;

            $item_fields = array();
        }

        $content['item_fields'] = $item_fields;
		$data['availMethods'] = $this->availMethods;

        // --------------------------------------------------------------------

		if( $data['pid'] )
		{
			$data['params'] = array();
			
			$qresult = SPIm::I('params')->manage->select( 'product', $cat );
			if( $qresult !== false )
			{
				while( $item = $qresult->fetch() )
				{
					$data['params'][] = $item;
				}
				$qresult->close();
			}
		}
		
        // --------------------------------------------------------------------

        if( is_array( $this->CONTENT_MODES[ $data['tmode'] ] ) && count( $this->CONTENT_MODES[ $data['tmode'] ] ) > 1 )
        {
            $data['list_types'] = $this->CONTENT_MODES[ $data['tmode'] ];
        }
        elseif( count( $this->CONTENT_MODES[ $data['tmode'] ] ) == 1 )
        {
            $data['const_type'] = $data['tmode'];
        }

        // --------------------------------------------------------------------

        $data['formvars'] = array();
        $data['formvars']['tmode']  = $data['tmode'];
        $data['formvars']['action'] = $data['formmode'];
		$data['formvars']['cat'] = $cat;
		$data['formvars']['pid'] = $data['pid'];

        if( $item_id )
        {
            $data['formvars']['iid'] = $item_id;
        }

        $data['link_form_submit'] = $this->pack_link();

        // --------------------------------------------------------------------

        return true;
    }

    private function exec_savedata( & $content, & $data )
    {
        if( false === ( $mFilters = SPIm::I('filters') ) )
        {
            return false;
        }

        if( in_array( $data['action'], array( 'insert', 'modify' ) ) === false )
        {
            trigger_error( 'Undefined action ('.$data['action'].')', E_USER_ERROR );
        }

        // --------------------------------------------------------------------

        if( $data['action'] == 'insert' )
        {
            $item_id = null;
        }
        else # modify
        {
            $item_id = (int) SPI::I('var')->get('iid');
        }
		
		$cat = (int) SPI::I('var')->get('cat');

        $in_values = SPI::I('var')->get('field');

        // --------------------------------------------------------------------

        $validator = SPIc::I('validator')->open();
		
        $validator->add_rule( 'workstatus',     'integer[0:1]' );
        $validator->add_rule( 'name',           'string[1:128]' );
		
		if( $data['pid'] )
		{
			$validator->add_rule( 'pid_params',     'integer[1:]' );
			$validator->add_rule( 'method_equal',   'string[1:3]' );
			$validator->add_rule( 'value',          'string[1:]' );
			$validator->add_rule( 'value_add',      'string' );
		}
		else
		{
			$validator->add_rule( 'description',    'string' );
		}

        if( is_array( $this->CONTENT_MODES[ $data['tmode'] ] ) && count( $this->CONTENT_MODES[ $data['tmode'] ] ) > 1 )
        {
            $validator->add_rule( 'tmode',   'select', array_keys( $this->CONTENT_MODES[ $data['tmode'] ] ) );
        }
        elseif( count( $this->CONTENT_MODES[ $data['tmode'] ] ) == 1 )
        {
            $validator->add_rule( 'tmode',   'select', array( $data['tmode'] ) );
        }

        list( $status, $validator_data ) = $validator->exec( $in_values );

        if( $status === false )
        {
            $response = array();
            $response['status'] = 'error';
            $response['error_messages'] = $validator_data; // as errors
			
            SPIv::I('json')->render($response);
            die();
        }

        // --------------------------------------------------------------------
        // Pre insert | modify actions

        $in_values = $validator_data; // as parsed values
		$in_values['value_add'] = $in_values['value_add'] ? $in_values['value_add'] : null;

        // --------------------------------------------------------------------
        // Do insert | modify

        if( $data['action'] == 'insert' )
        {
			$in_values['pid_catalog'] = $cat ? $cat : null;
			$in_values['pid'] = $data['pid'];
			
			$status = $mFilters->manage->insert( $in_values );

            if( $status !== false )
            {
                $item_id = $status;
                $status = true;
            }
        }
        else # modify
        {
            $status = $mFilters->manage->modify( $item_id, $in_values );
        }

        // --------------------------------------------------------------------

        if( $status === false )
        {
            $response = array();
            $response['status'] = 'error_alert';

            if( $data['action'] == 'insert' )
            {
                $response['error_message'] = 'При вставке данных возникла ошибка!';
            }
            else
            {
                $response['error_message'] = 'При сохранении данных возникла ошибка!';
            }
            
            SPIv::I('json')->render($response);
            die();
        }

        // --------------------------------------------------------------------

        $response = array();
        $response['status'] = 'complite';
        $response['link_redirect'] = $this->pack_link( $data['tmode'], array( 'action'=>'view', 'action_complite'=>$data['action'] ) );
        SPIv::I('json')->render($response);
        die();
    }

    private function exec_sortdata( & $content, & $data )
    {
        $data['title']    = SPI::I('lang')->content->{"title_{$data['tmode']}"};
        $data['subtitle'] = 'Сортировка элементов';
        $data['template'] = 'filters/sort.tpl';

        $data['link_back'] = $this->pack_link( $data['tmode'] );
		
		$cat = SPI::I('var')->get('cat');

        $qresult = SPIm::I('filters')->manage->select_for_sort( $data['tmode'], $cat, $data['pid'] );

        // --------------------------------------------------------------------
        // Generate List

        $data['items'] = array();

        while( $item = $qresult->fetch() )
        {
            $data['items'][ $item['id'] ] = $item;
        }
        $qresult->close();

        // --------------------------------------------------------------------

        $data['formvars'] = array();
        $data['formvars']['tmode']     = $data['tmode'];
        $data['formvars']['action']    = 'view';
        $data['formvars']['action_do'] = 'set_sort_order';
		$data['formvars']['cat']       = $cat;
		$data['formvars']['pid']       = $data['pid'];

        $data['link_form_submit'] = $this->pack_link();

        return true;
    }
}
